package com.atguigu.gmall.common.interceptor;

import com.atguigu.gmall.common.util.ReqUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Author:lyd
 * @Date:2023/9/1 18:37
 * @Version:1.0
 * @Description 配置一个拦截器，用来解决feign远程调用请求头丢失问题
 **/
@Component
public class RequestHearInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest request = ReqUtil.getOldRequest();
        if(request == null){
            return;
        }
        Enumeration<String> headerNames = request.getHeaderNames();
        //遍历请求头，重新放入新的请求
        while ((headerNames.hasMoreElements())) {
            String heardKey = headerNames.nextElement();
            //透传令牌；只把需要的请求头放在新的请求里面即可
            if ("cookie".equalsIgnoreCase(heardKey) ||
                    "token".equalsIgnoreCase(heardKey) ||
                    "userTempId".equalsIgnoreCase(heardKey)) {
                //获取请求头中的内容
                String headerValue = request.getHeader(heardKey);
                requestTemplate.header(heardKey, headerValue);
            }
        }
    }
}
